<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card >
       <el-row :gutter="20">
         <!-- <el-col :span="8"> -->
           <!-- el-col和el-input问题 相用会失去输入的 -->
         <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList" @change="getUserList">
         <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
         </el-input>
         <!-- </el-col> -->
         <el-row :span="4">
             <el-button type="primary" @click="openeddialog">添加用户</el-button>
         </el-row>
         </el-row>
        <!-- 表格 -->
        <el-table
          :data="userlist"
          stripe
          border
         >
      <el-table-column type="index" align="center"></el-table-column>
      <el-table-column prop="username" label="姓名"  align="center"></el-table-column>
      <el-table-column prop="email" label="邮箱"  align="center"></el-table-column>
      <el-table-column prop="mobile" label="电话"  align="center"></el-table-column>
      <el-table-column prop="role_name" label="角色"  align="center"></el-table-column>
      <el-table-column prop="mg_state" label="状态"  align="center">
          <template v-slot="scoped">
              <el-switch
               v-model="scoped.row.mg_state"
               @change="userStateChanged(scoped.row)">
              </el-switch>
          </template>
      </el-table-column>
      <el-table-column  label="操作"  align="center" width="180px">
          <template v-slot="scoped">
              <!-- 修改按钮 -->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="amenduser(scoped.row.id)"></el-button>
              <!-- 删除按钮 -->
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removebyID(scoped.row.id)"></el-button>
              <!-- 分配角色按钮 -->
              <el-tooltip class="item" effect="dark" content="分配对象" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-star-off" size="mini" @click="setRole(scoped.row)"></el-button>
              </el-tooltip>
          </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagesize"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
     </el-card>
     <!-- 添加用户对话框 -->
     <el-dialog
       title="添加用户信息"
       :visible.sync="dialogVisible"
        width="50%" @close="addclose">
      <el-form :model="addForm" :rules="addFromFules" ref="addFormRef" label-width="70px" >
      <el-form-item label="用户名" prop="username">
      <el-input v-model="addForm.username"></el-input>
      </el-form-item>
       <el-form-item label="密码" prop="password">
      <el-input v-model="addForm.password"></el-input>
      </el-form-item>
       <el-form-item label="邮箱" prop="email">
      <el-input v-model="addForm.email"></el-input>
      </el-form-item>
       <el-form-item label="手机" prop="mobile">
      <el-input v-model="addForm.mobile"></el-input>
      </el-form-item>
      </el-form>
         <span slot="footer" >
         <el-button @click="dialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
     </el-dialog>
     <!-- 修改用户对话框 -->
     <el-dialog
     title="修改用户信息"
     :visible.sync="modificationuser"
     width="50%"
     @close="modclose">
     <el-form :model="modificationuserForm" :rules="modificationuserFormRules" ref="modificationuserFormRefs" label-width="60px" class="demo-ruleForm">
     <el-form-item label="用户名">
     <el-input v-model="modificationuserForm.username" disabled></el-input>
     </el-form-item>
     <el-form-item label="邮箱" prop="email">
     <el-input v-model="modificationuserForm.email"></el-input>
     </el-form-item>
     <el-form-item label="手机" prop="mobile">
     <el-input v-model="modificationuserForm.mobile"></el-input>
     </el-form-item>
     </el-form>
     <span slot="footer" class="dialog-footer">
      <el-button @click="modificationuser = false">取 消</el-button>
      <el-button type="primary" @click="editUserInfo">确 定</el-button>
     </span>
     </el-dialog>
     <!-- 分配角色列表 -->
     <el-dialog title="分配对象" :visible.sync="setRoleDialogVisible" width="50%">
     <div>
       <p>当前用户:{{this.userInfo.username}}</p>
       <p>当前角色:{{this.userInfo.role_name}}</p>
       <p>分配新角色:
         <el-select v-model="selectRoleID" placeholder="请选择">
         <el-option
          v-for="item in roleList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
         </el-option>
  </el-select>
       </p>
     </div>
     <span slot="footer" class="dialog-footer">
     <el-button @click="setRoleDialogVisible = false">取 消</el-button>
     <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
</el-dialog>
    </div>
</template>
<script>
// import InputBar from "../input"
export default {
  // components:{
  //  InputBar
  // },
   data(){
     //定义校验邮箱的验证规则
     const checkemail=(rule,value,callback)=>{
          const regemail=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
          if(regemail.test(value)){
            return callback()
          }
          callback(new Error("请按正确邮箱规格输入"))
     }
     //定义校验手机的验证规则
     const checkphone=(rule,value,callback)=>{
       const regphone=/^1[3|4|5|7|8][0-9]{9}$/
       if(regphone.test(value)){
         return callback()
       }
       callback(new Error("请输入正确规格的手机号"))
     }
      return{ //获取用户数据列表的参数对象
      queryInfo:{
          //查询参数(搜索关键字  )
          query:"",
          //当前页数
          pagenum:1,
          //当前每页显示多少条数据
          pagesize:2
      },
      total:0,
      userlist:[],
      dialogVisible:false,
      addForm:{
        username:"",
        password:"",
        email:"",
        mobile:""
      },
      addFromFules:{
        username:[
       { required: true, message: '请输入用户名称', trigger: 'blur' },
       { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
       ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur'}
        ],
        mobile:[
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur'}
        ]
      },
       //控制修改用户对话框的显示与隐藏
       modificationuser:false,
       //查询到的用户信息对象
       modificationuserForm:{},
       modificationuserFormRefs:"",
       modificationuserFormRules:{
         email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur'}
         ],
         mobile:[
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur'}
         ]
       },
       //控制分配角色对话框的显示与隐藏
       setRoleDialogVisible:false,
       //需要被分配角色的用户信息
       userInfo:{},
       //所有角色的数据列表
       roleList:[],
       //新分配角色的绑定
       selectRoleID:""
     }
   },
   created(){
      this.getUserList()
   },
   methods:{
      async getUserList(){
         const {data:res}=await this.$http.get("users",{
              params:this.queryInfo
          })
        //   console.log(res)
          if(res.meta.status!==200){
              return this.$message.error("用户列表错误")
          }
          this.total=res.data.total,
          this.userlist=res.data.users
          this.pagenum=1
      },
      //监听 pagesize 改变的事件
     handleSizeChange(newSize){
         this.queryInfo.pagesize=newSize
         this.getUserList()
     },
      //监听 页码值 改变的事件
    handleCurrentChange(newPage){
        this.queryInfo.pagenum=newPage
        this.getUserList()
    },
    //监听Switch 开关状态的改变
   async userStateChanged(userinfo){
    //    console.log(userinfo)
      const {data:res}=await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
    if(res.meta.status!==200){
        //后台未修改 但前端页面已经按了 所有要取反回来
        userinfo.mg_state=!userinfo.mg_state
        return this.$message.error("修改用户状态失败")
    }
    this.$message.success("修改用户状态成功")
   },
   openeddialog(){
     this.dialogVisible=true
   },
   //监听添加用户对话框的关闭事件
   addclose(){
    this.$refs.addFormRef.resetFields()
   },
   //点击确定添加新用户
   addUser(){
     this.$refs.addFormRef.validate(async value=>{
       if(!value) return
       //发送请求
       const {data:res}=await this.$http.post("users",this.addForm)
       if(res.meta.status!==201)  this.$message.error("已有")
       this.$message.success("添加成功")
        //关闭窗口
       this.dialogVisible=false
       //刷新数据
       this.getUserList()
     })
   },
   async amenduser(id){
     this.modificationuser=true
     const {data:res}=await this.$http.get(`users/${id}`)
     if(res.meta.status!==200) return this.$message.error("查找错误")
     this.modificationuserForm=res.data
   },
  //  重置修改用户表单
   modclose(){
     this.$refs.modificationuserFormRefs.resetFields()
   },
   //预验证修改用户表单
  editUserInfo(){
     this.$refs.modificationuserFormRefs.validate(async value=>{
       if(!value) return 
       const {data:res}=await this.$http.put("users/"+this.modificationuserForm.id,{
         email:this.modificationuserForm.email,
         mobile:this.modificationuserForm.mobile
       })
       if(res.meta.status!==200) return 
       //关闭窗口
       this.modificationuser=false
       //刷新页面数据
       this.getUserList()
       //反馈显示修改成功
       this.$message.success("修改成功")
     })
   },
  async removebyID(id){
      const confirmResult=await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        // console.log(confirmResult)
        //按确认删除会控制台会返回一个confirm 取消会返回cancel
        if(confirmResult!=="confirm") return this.$message.info("已取消")
        const {data:res}=await this.$http.delete("users/"+id)
        if(res.meta.status!==200) return this.$message.error("删除失败")
        this.$message.success("删除成功")
        this.getUserList()
   },
   async setRole(userInfo){
     this.userInfo=userInfo
     //在展示对话框之前,获取所有角色的列表
     const {data:res}=await this.$http.get("roles")
     if(res.meta.status!==200) return $this.$message.error("获取列表失败")
     this.roleList=res.data
     console.log(this.roleList)
     this.setRoleDialogVisible=true
   },
   async saveRoleInfo(){
    //  if(!this.selectRoleID){
    //    return this.$message.error("请选择要分配的角色")
    //  }
     console.log(this.userInfo.id,this.selectRoleID)
     const {data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectRoleID})
     if(res.meta.status!==200) return this.$message.error("更新用户失败")
     this.$message.success("更新成功")
     this.getUserList()
     this.setRoleDialogVisible=false
     //分配上没有修改成功
   }
  }
}
</script>
<style lang="scss" scoped>

</style>